package com.neutech.controller;

import com.google.gson.Gson;
import com.neutech.entity.User;
import com.neutech.service.UserService;
import com.neutech.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/user/login")
public class LoginServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader bufferedReader = req.getReader();
        StringBuilder requestBody = new StringBuilder();
        String  tmp = null;
        while ((tmp = bufferedReader.readLine()) != null) {
            requestBody.append(tmp);
        }

        User user = new Gson().fromJson(requestBody.toString(),User.class);
        bufferedReader.close();

        PrintWriter out = resp.getWriter();

        out.print(new Gson().toJson(userService.login(user,req.getSession())));
        out.close();
    }
}
